package cn.edu.seu.ssny.controller.web;

import cn.edu.seu.ssny.common.ExportExcelUtils;
import cn.edu.seu.ssny.common.JsonResult;
import cn.edu.seu.ssny.common.utils.DateUtils;
import cn.edu.seu.ssny.controller.BaseController;
import cn.edu.seu.ssny.entity.*;
import cn.edu.seu.ssny.service.IDeviceCategoryService;
import cn.edu.seu.ssny.service.IDeviceDataService;
import cn.edu.seu.ssny.service.IDeviceDataStdService;
import cn.edu.seu.ssny.service.IDeviceService;
import cn.edu.seu.ssny.service.specification.SimpleSpecificationBuilder;
import cn.edu.seu.ssny.service.specification.SpecificationOperator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.util.*;

import static cn.edu.seu.ssny.common.utils.DateUtils.*;

@Controller
@RequestMapping("/web/analysis")
public class AnalysisController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(AnalysisController.class);


    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IDeviceDataStdService deviceDataStdService;

    @Autowired
    private IDeviceCategoryService deviceCategoryService;


    @RequestMapping(value = { "/efficiency"})
    public String efficiencyLive(ModelMap map, HttpSession session) {
        return "web/analysis/efficiency";
    }

    @RequestMapping(value = { "/efficiency-history"})
    public String efficiencyHistory(ModelMap map, HttpSession session) {
        return "web/analysis/efficiency-history";
    }

    @RequestMapping(value = { "/pipenet"})
    public String pipeNet(ModelMap map, HttpSession session) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("mode", "hour");
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Double lengdong =  deviceDataStdService.getPumpCoefficient(timeList, (Project)session.getAttribute("currProject"), "冷冻水泵");
        Double lengque =  deviceDataStdService.getPumpCoefficient(timeList, (Project)session.getAttribute("currProject"), "冷却水泵");
        map.put("lengdong", lengdong.isNaN()? "-": lengdong);
        map.put("lengque", lengque.isNaN()? "-": lengdong);
        return "web/analysis/pipenet";
    }

    @RequestMapping(value = { "/heat-balance"})
    public String heatBalance(ModelMap map, HttpSession session) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("mode", "hour");
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Map<String, Object> balanceMap =  deviceDataStdService.getHeatBalanceCoefficient(timeList, (Project)session.getAttribute("currProject"));
        map.putAll(balanceMap);
        return "web/analysis/heat-balance";
    }

    @RequestMapping(value = { "/efficiency/live/data"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult efficiencyLiveData(@RequestBody Map<String,Object> jsonMap, HttpSession session) {
        Map<String, Object> rtn = new HashMap<>();
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(jsonMap));
        String mode = json.get("mode").toString();
        String chString = json.get("chString").toString();
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Map<String, List<Double>> copCHMap =  deviceDataStdService.getCopCH(timeList, (Project)session.getAttribute("currProject"), mode, chString);
        // 去除第一个时间
        timeList.remove(timeList.get(0));
        List<String> xList = new ArrayList<>();
        for(Date date: timeList)
            xList.add(DateUtils.format(date, getPattern(mode)));
        List<String> legends = new ArrayList<>();
        List<List<Double>> yLists = new ArrayList<>();
        for(Map.Entry<String, List<Double>> entry: copCHMap.entrySet()) {
            legends.add(entry.getKey());
            yLists.add(entry.getValue());
        }
        rtn.put("xList", xList);
        rtn.put("tag", "");
        rtn.put("title", "COP");
        rtn.put("legends", legends);
        rtn.put("yLists", yLists);

        return JsonResult.success("操作成功", rtn);
    }

    @RequestMapping(value = { "/efficiency/live/data-sys"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult efficiencyLiveDataSystem(@RequestBody Map<String,Object> jsonMap, HttpSession session) {
        Map<String, Object> rtn = new HashMap<>();
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(jsonMap));
        String mode = json.get("mode").toString();
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Map<String, List<Double>> copCHMap =  deviceDataStdService.getCopCHAll(timeList, (Project)session.getAttribute("currProject"), mode);
        // 去除第一个时间
        timeList.remove(timeList.get(0));
        List<String> xList = new ArrayList<>();
        for(Date date: timeList)
            xList.add(DateUtils.format(date, getPattern(mode)));
        List<String> legends = new ArrayList<>();
        List<List<Double>> yLists = new ArrayList<>();
        /*
        for(Map.Entry<String, List<Double>> entry: copCHMap.entrySet()) {
            legends.add(entry.getKey());
            yLists.add(entry.getValue());
        }
        */
        legends.add("系统");
        for(Map.Entry<String, List<Double>> entry: copCHMap.entrySet()) {
            if(yLists.size() == 0)
                yLists.add(entry.getValue());
            else {
                for(int i = 0; i < yLists.get(0).size(); i++) {
                    yLists.get(0).set(i, yLists.get(0).get(i)+entry.getValue().get(i));
                }
            }
        }
        rtn.put("xList", xList);
        rtn.put("tag", "");
        rtn.put("title", "COPs");
        rtn.put("legends", legends);
        rtn.put("yLists", yLists);

        return JsonResult.success("操作成功", rtn);
    }


    @RequestMapping(value = { "/pipenet/data"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult pipenetData(@RequestBody Map<String,Object> jsonMap, HttpSession session) {
        Map<String, Object> rtn = new HashMap<>();
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(jsonMap));
        String mode = json.get("mode").toString();
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Map<String, List<Double>> map =  deviceDataStdService.getPumpEff(timeList, (Project)session.getAttribute("currProject"), mode);
        // 去除第一个时间
        timeList.remove(timeList.get(0));
        List<String> xList = new ArrayList<>();
        for(Date date: timeList)
            xList.add(DateUtils.format(date, getPattern(mode)));
        List<String> legends = new ArrayList<>();
        List<List<Double>> yLists = new ArrayList<>();
        for(Map.Entry<String, List<Double>> entry: map.entrySet()) {
            legends.add(entry.getKey());
            yLists.add(entry.getValue());
        }
        rtn.put("xList", xList);
        rtn.put("tag", "");
        rtn.put("title", "效率：%");
        rtn.put("legends", legends);
        rtn.put("yLists", yLists);

        return JsonResult.success("操作成功", rtn);
    }


    @RequestMapping(value = { "/heat-balance/data"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult heatBalanceData(@RequestBody Map<String,Object> jsonMap, HttpSession session) {
        Map<String, Object> rtn = new HashMap<>();
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(jsonMap));
        String mode = json.get("mode").toString();
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Map<String, List<Double>> map =  deviceDataStdService.getBalanceTemp(timeList, (Project)session.getAttribute("currProject"), mode);
        // 去除第一个时间
        timeList.remove(timeList.get(0));
        List<String> xList = new ArrayList<>();
        for(Date date: timeList)
            xList.add(DateUtils.format(date, getPattern(mode)));
        List<String> legends = new ArrayList<>();
        List<List<Double>> yLists = new ArrayList<>();
        for(Map.Entry<String, List<Double>> entry: map.entrySet()) {
            legends.add(entry.getKey());
            yLists.add(entry.getValue());
        }
        rtn.put("xList", xList);
        rtn.put("tag", "");
        rtn.put("title", "温度：℃");
        //rtn.put("legends", legends);
        rtn.put("yLists", yLists);

        return JsonResult.success("操作成功", rtn);
    }

    @RequestMapping(value = { "/heat-change/data"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult heatChangeData(@RequestBody Map<String,Object> jsonMap, HttpSession session) {
        Map<String, Object> rtn = new HashMap<>();
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(jsonMap));
        String mode = json.get("mode").toString();
        jsonMap.put("startTimeSearch", "2021-01-19 08:00:00");
        jsonMap.put("endTimeSearch", "2021-01-20 23:50:00");
        List<Date> timeList = getTimeListUsage(jsonMap);
        Map<String, List<Double>> map =  deviceDataStdService.getBuriedPipeLine(timeList, (Project)session.getAttribute("currProject"), mode);
        // 去除第一个时间
        timeList.remove(timeList.get(0));
        List<String> xList = new ArrayList<>();
        for(Date date: timeList)
            xList.add(DateUtils.format(date, getPattern(mode)));
        List<String> legends = new ArrayList<>();
        List<List<Double>> yLists = new ArrayList<>();
        for(Map.Entry<String, List<Double>> entry: map.entrySet()) {
            legends.add(entry.getKey());
            yLists.add(entry.getValue());
        }
        rtn.put("xList", xList);
        rtn.put("tag", "");
        rtn.put("title", "换热量：W/m");
        //rtn.put("legends", legends);
        rtn.put("yLists", yLists);

        return JsonResult.success("操作成功", rtn);
    }

    private Map<String, Object> packetData(Map<String,Object> jsonMap) {
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(jsonMap));
        String mode = json.get("mode").toString();

        int[] xList = {1,2,3,4,5};
        int[][] yLists = {{1,2,3,4,5},{3,1,4,6,2}};
        String tag = "m";
        String title = "test";
        String[] legends = new String[]{mode+": data1", "data2"};
        Map<String, Object> rtn = new HashMap<>();
        rtn.put("xList", xList);
        rtn.put("tag", tag);
        rtn.put("title", title);
        rtn.put("legends", legends);
        rtn.put("yLists", yLists);
        return rtn;
    }

}
